package com.example.chamberlainserver.Service.impl;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.example.chamberlainserver.Service.SmsService;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.concurrent.CompletableFuture;

@Service
public class SmsServiceImpl implements SmsService {
    @Value("${ALIBABA_CLOUD_ACCESS_KEY_ID}")
    private String ACCESSID;

    @Value("${ALIBABA_CLOUD_ACCESS_KEY_SECRET}")
    private String ACCESS_KEY_SECRET;

    @Override
    public CompletableFuture<Boolean> sendSms(String signName, String templateCode, String phoneNumbers, String templateParam) {
        System.out.println("id：" + this.ACCESSID + "key：" + this.ACCESS_KEY_SECRET);
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(this.ACCESSID)
                .accessKeySecret(this.ACCESS_KEY_SECRET)
                .build());

        AsyncClient client = AsyncClient.builder()
                .region("cn-shenzhen")
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                )
                .build();

        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName(signName)
                .templateCode(templateCode)
                .phoneNumbers(phoneNumbers)
                .templateParam(templateParam)
                .build();

        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);

        return response.thenApply(resp -> {
            System.out.println(new Gson().toJson(resp));
            client.close();
            return resp.getStatusCode() == 200;
        }).exceptionally(throwable -> {
            System.err.println("短信发送失败: " + throwable.getMessage());
            client.close();
            return false;
        });
    }
}